package com.ptma.controllers;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ptma.model.User;
import com.ptma.repository.GenericRepo;

@Controller("/register")
public class RegistrationController {

	@Autowired
	private GenericRepo<User, Serializable> userService;

	@ResponseBody
	@RequestMapping(value = "/register.html", method = RequestMethod.POST)
	public ModelAndView processRegistration(@ModelAttribute("user") User u,
			Model model, BindingResult result) {

		if (result.hasErrors()) {
			return new ModelAndView("registration");
		} else {

			User user = new User();
			user.setEmail(u.getEmail().toLowerCase());
			user.setPassword(u.getPassword());

			user.setFirstName(u.getFirstName());
			user.setLastName(u.getLastName());

			userService.save(user);
		}
		return new ModelAndView("login");

	}
}
